
const router = require('koa-router')();
const util = require("../common/utils")
const { sequelize } = require('../common/dbs')
// navinfo
const navModel = require("../models/nav_list")
const navinfo = navModel(sequelize);

const navShareModel = require("../models/nav_share")
const navshare = navShareModel(sequelize);

const navTypeModel = require("../models/nav_type")
const navTypeinfo = navTypeModel(sequelize);

const userModel = require("../models/email_user")
const userinfo = userModel(sequelize);

const navLikeModel = require("../models/nav_list_like")
const navinfoLike = navLikeModel(sequelize);

const { QueryTypes } = require('sequelize');

// 根据类型返回列表
router.get('/list', async (ctx) => {
    try {
        let reqQuery = ctx.request.query;
        // 多对多关系 有个中间表
        navTypeinfo.belongsToMany(navinfo, { through: navshare, foreignKey: 'typeid' });
        navinfo.belongsToMany(navTypeinfo, { through: navshare, foreignKey: 'nav_id' });
        // // 查喜欢表
        let navData2 = await navTypeinfo.findAll(
            {
                attributes: ['typename'],
                include: [
                    {
                        attributes: ['ntitle', 'ndetail', 'nurl', 'fileId'],
                        model: navinfoLike,
                        through: {
                            attributes: [], //不返回
                            where: { share_id: reqQuery.id }
                        }
                    },
                ],
            });
        navTypeinfo.belongsToMany(navinfoLike, { through: navshare, foreignKey: 'typeid' });
        navinfoLike.belongsToMany(navTypeinfo, { through: navshare, foreignKey: 'nav_id' });

        // // 查分享表
        let navData1 = await navTypeinfo.findAll(
            {
                attributes: ['typename'],
                include: [
                    {
                        attributes: ['ntitle', 'ndetail', 'nurl', 'fileId'],
                        model: navinfo,
                        through: {
                            attributes: [], //不返回
                            where: { share_id: reqQuery.id }
                        }
                    },

                ],
            });
        if (navData1.length > 0) {
            navData2 = navData2.concat(navData1)
        }
        let newListKey = []
        let newList = []
        // 重新组合
        navData2.forEach(element => {
            let index = newListKey.indexOf(element.typename)
            if (index != -1) {
                element.lists.map(item => {
                    newList[index].lists.push(item)
                })
            } else {
                newListKey.push(element.typename)
                newList.push(element)
            }
        });

        // // 只返回有数据的类型
        let dataNoNull = []
        newList.map(item=>{
            if(item.lists.length>0){
                dataNoNull.push(item)
            }
        })
        ctx.body = util.resultSuccess({ data: dataNoNull });
    } catch (err) {
        ctx.body = util.resultError({ data: null });
    }
})

// 生成分享链接
router.post('/createShare', async (ctx) => {
    try {
        let share_id = getuuid()
        let user_id = await getUserID(ctx)
        let valueArr = [];
        let reqBody = ctx.request.body;
        for (let i = 0; i < reqBody.shares.length; i++) {
            var value = {
                nav_id: reqBody.shares[i].id,
                typeid: reqBody.shares[i].typeid,
                id: getuuid(),
                share_id: share_id,
                userid: user_id

            };
            valueArr.push(value)
        }
        let res = await navshare.bulkCreate(valueArr, { updateOnDuplicate: ["nav_id", "typeid", "id", "share_id", "userid"] });
        if (res.length == reqBody.shares.length) {
            ctx.body = util.resultSuccess({ data: { share_id: share_id } });
        } else if (res.length == 0) {
            ctx.body = util.resultError({ data: '生成分享链接失败' });
        } else {
            ctx.body = util.resultError({ data: '生成链接失败' });
        }

    } catch (err) {
        ctx.body = util.resultError({ data: err });
    }
})
function getuuid() {
    let s = [];
    let hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
    var uuid = s.join("");
    return uuid;
}
function Cookie(name, cookies) {
    var CookieValue = null;
    if (cookies) {
        var Cookies = cookies.split(";");
        for (var i = 0; i < Cookies.length; i++) {
            var Cookie = (Cookies[i] || "").replace(/^\s+|\s+$/g, "");
            //这个if写的屌
            if (Cookie.substring(0, name.length + 1) == (name + '=')) {
                CookieValue = decodeURIComponent(Cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return CookieValue;
}
async function getUserID(ctx) {
    // console.log('cookie--->>', ctx.request.header)
    let token = Cookie('token', ctx.request.header.cookie)
    token = token ? token : ctx.request.header.authorization

    if (!token) {
        return ''
    }
    let userData = await userinfo.findOne(
        {
            where: {
                token: token
            },
        }
    );
    console.log('userData', userData._id);
    if (userData) {
        return userData._id
    } else {

        return '-1'
    }
}
module.exports = router.routes();